from ui.mainWindow import WinGUI
import subprocess
from tkinter import messagebox
import re
import threading

class Win(WinGUI):
    def __init__(self):
        super().__init__()
        self.__event_bind()
        self.__validation_bind()
        self.__init_value()



    # #-----------------事件处理-----------------------------
    def show_result(self):
        def thread_function():
            self.tk_button_reflesh.config(state='disabled')
            self.tk_button_submit.config(state='disabled')
            powershell_command = f"netsh interface portproxy show all"
            result = subprocess.run(['powershell', "-NoProfile", '-Command', powershell_command], capture_output=True, text=True, creationflags=subprocess.CREATE_NO_WINDOW)
            pattern = r'(\S+)\s+(\d+)\s+(\S+)\s+(\d+)'
            matches = re.findall(pattern, result.stdout)
            self.tk_table_result.delete(*self.tk_table_result.get_children()) # 清空数据
            for id, match in enumerate(matches):
                row = (id, match[0], match[1], match[2], match[3])
                self.tk_table_result.insert("", index="end", values=row)
            self.tk_button_reflesh.config(state='normal')
            self.tk_button_submit.config(state='normal')
        t = threading.Thread(target=thread_function)
        t.start()



    def delete(self,evt):
        ask = messagebox.askquestion("警告", "确定要删除吗？", icon='warning')
        if ask == 'no':
            return
        item = self.tk_table_result.focus()  # 获取被双击的行
        values = self.tk_table_result.item(item, "values")  # 获取该行的数据
        local_host, local_port = values[1], values[2]
        powershell_command = f"netsh interface portproxy delete v4tov4 listenport={local_port} listenaddress={local_host}"
        result = subprocess.run(['powershell', "-NoProfile", '-Command', powershell_command], capture_output=True, text=True, creationflags=subprocess.CREATE_NO_WINDOW)
        self.show_result()
        messagebox.showinfo("提示", "成功删除")


    def submit(self):
        def thread_function():

            local_host = self.tk_input_local_host.get()
            local_port = self.tk_input_local_port.get()
            remote_host = self.tk_input_remote_host.get()
            remote_port = self.tk_input_remote_port.get()
            if local_host=='' or local_port=='' or remote_host=='' or remote_port=='':
                messagebox.showwarning("警告", "请将信息填写完整")
                return
            self.tk_button_submit.config(state='disabled')
            powershell_command = f"netsh interface portproxy add v4tov4 listenport={local_port} listenaddress={local_host} connectport={remote_port} connectaddress={remote_host}"
            result = subprocess.run(['powershell', "-NoProfile", '-Command', powershell_command], capture_output=True, text=True, creationflags=subprocess.CREATE_NO_WINDOW)

            if result.stdout == '\n':
                self.show_result()
                messagebox.showinfo("成功", "端口转发成功")
            else:
                messagebox.showerror("错误", result.stdout)
            self.tk_button_submit.config(state='normal')

        t = threading.Thread(target=thread_function)
        t.start()
        
    # #-----------------校验绑定-----------------------------
    def validate_input_host(self, text):
        if len(text) == 0 or text[-1] in ['.', '*', '0', '1', '2', '3','4','5','6','7','8','9', 'l', 'o', 'c', 'a', 'h', 's', 't']:
            return True
        else:
            return False
        
    def validate_input_port(self, text):
        if len(text) == 0 or text[-1] in ['0', '1', '2', '3','4','5','6','7','8','9']:
            return True
        else:
            return False
    def __event_bind(self):
        self.tk_table_result.bind('<Double-Button-1>', self.delete)
        self.tk_button_submit.config(command=self.submit)
        self.tk_button_reflesh.config(command=self.show_result)
        pass

    def __validation_bind(self):
        self.tk_input_local_host.config(validate="key", validatecommand=(self.register(self.validate_input_host), '%P'))
        self.tk_input_local_port.config(validate="key", validatecommand=(self.register(self.validate_input_port), '%P'))
        self.tk_input_remote_host.config(validate="key", validatecommand=(self.register(self.validate_input_host), '%P'))
        self.tk_input_remote_port.config(validate="key", validatecommand=(self.register(self.validate_input_port), '%P'))

    def __init_value(self):

        self.tk_input_local_host.insert(0, '0.0.0.0')
        self.tk_input_remote_host.insert(0, '')

        self.tk_table_result.insert("", index="end", values=("*", "正在查询...", "正在查询...", "正在查询...", "正在查询..."))
        self.show_result()

if __name__ == "__main__":
    win = Win()
    win.mainloop()
